import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import remarkMath from 'remark-math';
import remarkGfm from 'remark-gfm';
import remarkBreaks from 'remark-breaks';
import rehypeKatex from 'rehype-katex';
import CodeBlock from './CodeBlock';
import Reference from './Reference';
import CustomControl from './CustomControl';
import FormRenderer from './FormRenderer';
import mdStyles from '../styles/markdown.module.scss';

import styles from '../styles/Reference.module.css';

import { SvgIcon } from '@/components/icon';

import {
  Tooltip,
  Rate,
  App,
  Tag,
  Collapse,
  CollapseProps,
  Input,
  InputNumber,
  Select,
  Cascader,
  Button,
} from 'antd';
import appService from '@/api/services/appService';
import { useParams } from '@/router/hooks';
import { useDebounceFn, useInViewport, useSize } from 'ahooks';
import type { ChatItem, ThoughtChainItem } from '@/types/chat';
import { useIsDeepMode } from '@/store/chatStore';

import ThoughtChainALL from './ThoughtChainALL';

import { removeRefTags, fixUrlPunctuation, convertImageNames } from '@/utils/regexRules';

import { useConfig } from '@/store/configStore';

import { useBrowserCompatibility } from '@/hooks/event/use-browser-compatibility';

import GuessYouWantToAsk from './GuessYouWantToAsk';

import { useOrchestrationStore } from '@/store/orchestrationStore';
import { createMarkdownComponents } from './MarkdownComponents';
import ToolCallCollapse from './ToolCallCollapse';
import QuestionTip from '@/components/tooltip/QuestionTip';
import { UserSelectOptionItemType } from '@/types/workflow/template/system/interactive/type';
import { AppType } from '@/common/app/constants';
import { fetchConfigStatus } from '@/utils/common';
import useWindowWidth from '@/hooks/event/use-window-width';

interface FormItem {
  type: string;
  key: string;
  label: string;
  description?: string;
  value?: string | number | string[];
  defaultValue?: string | number | string[];
  valueType: string;
  required: boolean;
  list?: Array<{
    label: string;
    value: string;
    children?: Array<{
      label: string;
      value: string;
      children?: Array<{
        label: string;
        value: string;
      }>;
    }>;
  }>;
}

interface ChatProps {
  item: ChatItem;
  index: number;
  hideItem?: boolean;
  isLastOne?: boolean;
  deleteMessage?: (index: number) => void;
  reFreshAnswer?: (index: number) => void;
  scrollToBottom?: () => void;
  handleSend: (message: string, isUserSelect?: boolean) => void;
  isMessageSend?: boolean;
  guessQuestions?: { id: string; content: string }[];
  onQuestionClick?: (question: string) => void;
  workflowDebug?: boolean;
}

const MessageItem = ({
  item,
  index,
  hideItem,
  isLastOne,
  deleteMessage,
  reFreshAnswer,
  handleSend,
  scrollToBottom,
  isMessageSend,
  guessQuestions,
  onQuestionClick,
  workflowDebug = false,
}: ChatProps) => {
  const { title } = useConfig();
  const [isExpanded, setIsExpanded] = useState(false);
  const ref = useRef(null);
  const [inViewport] = useInViewport(ref);
  const [isShow, setIsShow] = useState(true);
  const [defaultCollectionId, setDefaultCollectionId] = useState<string>('');
  const size = useSize(ref);
  const isDeepMode = useIsDeepMode();
  const [keyArr, setKeyArr] = useState<string[]>([]);
  const { isSupported } = useBrowserCompatibility();

  const { configurations, subAppDetail } = useOrchestrationStore();
  const { message } = App.useApp();
  const { isPc } = useWindowWidth();

  // const quoteConfig = configurations?.find((config) => config.name === 'quote_enable');
  // const isQuote = quoteConfig?.default_value === '1' || quoteConfig?.default_value === true;

  const isQuote = useMemo(() => {
    const isQuoteEnable = fetchConfigStatus(configurations, 'quote_enable', true);
    const isSubQuoteEnable = fetchConfigStatus(subAppDetail?.configurations, 'quote_enable', true);
    return subAppDetail ? isSubQuoteEnable : isQuoteEnable;
  }, [configurations, subAppDetail]);

  const replaceNewlinesWithBr = useCallback((str: string) => {
    return str.trim().replace(/\n/g, '<br>');
  }, []);

  const initCollectionId = useCallback(() => {
    setDefaultCollectionId('');
  }, []);

  const preprocessMarkdown = useCallback((text: string): string => {
    let processedText = text;

    try {
      processedText = removeRefTags(processedText);
      processedText = fixUrlPunctuation(processedText);
      processedText = convertImageNames(processedText);
    } catch (error) {
      console.error('Error during markdown preprocessing:', error);
    }

    return processedText;
  }, []);

  const [thoughtListAll, setThoughtListAll] = useState<ThoughtChainItem>([]);

  const removeThinkTags = useCallback((text: string) => {
    // 使用正则表达式匹配<think>标签及其内容，并将其替换为空字符串
    return text.replace(/<think>.*?<\/think>/gs, '');
  }, []);

  const extractThinkContents = useCallback((text: string) => {
    const regex = /<think>(.*?)<\/think>/gs;
    let matches;
    const thinkContents: string[] = [];

    while ((matches = regex.exec(text)) !== null) {
      thinkContents.push(matches[1]); // 将捕获组的内容（标签内的文本）添加到数组中
    }

    return thinkContents;
  }, []);

  const extractThinkContents1 = useCallback((text: string) => {
    const regex = /<think>\s*([\s\S]*)/gs;
    let matches;
    const thinkContents: string[] = [];

    while ((matches = regex.exec(text)) !== null) {
      thinkContents.push(matches[1]); // 将捕获组的内容（标签内的文本）添加到数组中
    }

    return thinkContents;
  }, []);

  const isThinking = useCallback(() => {
    if (
      (item.text?.trimStart()?.startsWith('<think') && !item.text?.includes('</think>')) ||
      (item?.text?.trimStart() && '<think'.includes(item?.text?.trimStart()))
    ) {
      return true;
    } else {
      return false;
    }
  }, [item.text]);

  // 缓存处理后的文本和 parts 数组
  const { processedText, parts } = useMemo(() => {
    const processedText = preprocessMarkdown(isThinking() ? '' : removeThinkTags(item.text || ''));
    
    // 新增：将 processedText 拆分为文本和占位符
    const toolCallRegex = /__TOOL_CALL_([\w-]+)__/g;
    const parts: (string | { id: string })[] = [];
    let lastIndex = 0;
    let match;
    while ((match = toolCallRegex.exec(processedText)) !== null) {
      if (match.index > lastIndex) {
        parts.push(processedText.slice(lastIndex, match.index));
      }
      parts.push({ id: match[1] });
      lastIndex = match.index + match[0].length;
    }
    if (lastIndex < processedText.length) {
      parts.push(processedText.slice(lastIndex));
    }
    
    return { processedText, parts };
  }, [item.text, preprocessMarkdown, isThinking, removeThinkTags]);

  // 缓存 markdown components
  const markdownComponents = useMemo(() => {
    return createMarkdownComponents({
      handleSend,
      setDefaultCollectionId,
    });
  }, [handleSend, setDefaultCollectionId]);

  useEffect(() => {
    const isThink = isThinking();

    if (item.text) {
      const extractedContents = isThink
        ? extractThinkContents1(item.text)
        : extractThinkContents(item.text);
      const Arr = [];
      if (item.thinkList && item.thinkList.length > 0) {
        setKeyArr(['1', '2']);
        const thinkNodes = Array.from(item.thinkList ?? []);
        if (isDeepMode) {
          if (
            (item.text.length > 10 || item.text.startsWith('\n<think>')) &&
            thinkNodes.length > 0 &&
            !isThinking()
          ) {
            const thoughtItem = {
              title: '组织答案',
              description: '暂无',
              status: 'success',
              id: 'sdfadfadsf',
            };
            thinkNodes.push(thoughtItem);
          }
        } else {
          if (item.text.length > 1 && thinkNodes.length > 0 && !isThinking()) {
            const thoughtItem = {
              title: '组织答案',
              description: '暂无',
              status: 'success',
              // icon: getStatusIcon('success'),
            };
            thinkNodes.push(thoughtItem);
          }
        }

        Arr.push({
          label: (
            <div className="flex items-center">
              {isMessageSend && isLastOne ? (
                <SvgIcon icon="chat-workflow-run" size={16} color="var(--text-4)"></SvgIcon>
              ) : (
                <SvgIcon icon="chat-workflow-run" size={16} color="var(--text-4)"></SvgIcon>
              )}

              <span className="ml-2 text-[14px] font-font-weight-400 text-text-4">
                {'工作流执行'}
              </span>
            </div>
          ),
          children: (
            <div className="flex flex-wrap gap-2">
              {thinkNodes?.map((thinkItem, thinkIndex) => {
                return (
                  <span className="flex items-center" key={thinkItem.title}>
                    <Tag
                      color="rgba(255, 255, 255, 1)"
                      // color="var(--brand-color-light)"
                      key={thinkItem.title}
                      bordered={false}
                      className="rounded-[6px] font-font-weight-600"
                      style={{
                        fontSize: '14px',
                        color: 'var(--brand-color)',
                        height: '30px',
                        lineHeight: '30px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}
                    >
                      <div className="flex items-center justify-center">
                        {thinkNodes?.length - 1 === thinkIndex && isMessageSend && isLastOne ? (
                          <SvgIcon
                            icon="line-md--loading-alt-loop"
                            size={16}
                            color="var(--brand-color)"
                            className="mr-2"
                          ></SvgIcon>
                        ) : (
                          <SvgIcon
                            icon="ai-chat-done"
                            color="var(--brand-color)"
                            size="16"
                            className="mr-2"
                          />
                        )}
                        {thinkItem.title}
                      </div>
                    </Tag>
                    {thinkNodes?.length - 1 === thinkIndex ? (
                      <React.Fragment>
                        {/* {isMessageSend && isLastOne ? (
                          <SvgIcon
                            icon="line-md--loading-alt-loop"
                            size={20}
                            color="var(--brand-color-hover)"
                          ></SvgIcon>
                        ) : (
                          ''
                        )} */}
                      </React.Fragment>
                    ) : (
                      <SvgIcon
                        icon="line-md--arrow-small-right"
                        size={20}
                        color="var(--brand-color)"
                      ></SvgIcon>
                    )}
                  </span>
                );
              })}
            </div>
          ),
          key: '1',
        });
      }

      if (extractedContents.length > 0) {
        Arr.push({
          label: (
            <div>
              {isMessageSend && isThink ? (
                <div className="flex items-center">
                  <SvgIcon icon="rj-dot-rotate" size={16} color="var(--text-3)"></SvgIcon>
                  <span className="ml-3 text-[14px] font-normal text-[#4E5969]">
                    {'问题思考中...'}
                  </span>
                </div>
              ) : (
                <div className="flex items-center">
                  <SvgIcon icon="rj-dot-static" size={16} color="var(--text-3)"></SvgIcon>
                  <span className="ml-3 text-[14px] font-normal text-[#4E5969]">{'问题思考'}</span>
                </div>
              )}
            </div>
          ),
          children: (
            <div className="flex w-full">
              <div
                className="text-grays"
                style={{ borderLeft: '2px solid #00134d0f', paddingLeft: '10px' }}
              ></div>

              <div
                className="text-text-3"
                style={{
                  width: '100%',
                  wordWrap: 'break-word',
                  whiteSpace: 'normal',
                }}
                dangerouslySetInnerHTML={{ __html: replaceNewlinesWithBr(extractedContents[0]) }}
              />
            </div>
          ),
          key: '2',
        });
      }

      if (!isMessageSend && isLastOne) {
        setTimeout(() => {
          setKeyArr(['1', '2']);
        }, 0);
      }

      setThoughtListAll(Arr);
    }
  }, [item, isDeepMode, isMessageSend, isLastOne, isThinking, extractThinkContents1, extractThinkContents, replaceNewlinesWithBr]);

  const handleReferenceChange = useCallback((value: boolean) => {
    setIsExpanded(value);
  }, []);

  const { run, cancel, flush } = useDebounceFn(
    () => {
      if (isShow) {
        setIsShow(true);
      }
    },
    {
      wait: 15,
    },
  );

  useEffect(() => {
    if (hideItem && !inViewport && !isLastOne) {
      run();
    } else {
      cancel();
    }
  }, [inViewport, hideItem, isLastOne, run, cancel]);

  const [formValues, setFormValues] = useState<Record<string, any>>({});
  const [userSelectValue, setUserSelectValue] = useState<any>();

  // 检查必填项是否已填写
  const checkRequiredFields = useCallback((formItems: FormItem[]) => {
    const emptyRequiredFields: FormItem[] = [];

    formItems.forEach((item) => {
      if (item.required && (!formValues[item.key] || formValues[item.key] === '')) {
        emptyRequiredFields.push(item);
      }
    });

    if (emptyRequiredFields.length > 0) {
      const fieldNames = emptyRequiredFields
        .filter((field) => field.label)
        .map((field) => field.label)
        .join('、');
      message.warning(`请填写必填项${fieldNames ? ': ' + fieldNames : ''}`);

      // 聚焦到第一个未填写的字段
      const firstEmptyField = document.querySelector(
        `[data-key="${emptyRequiredFields[0].key}"]`,
      ) as HTMLElement;
      if (firstEmptyField) {
        const input = firstEmptyField.querySelector('input, .ant-select-selector') as HTMLElement;
        if (input) {
          input.focus();
        }
      }
      return false;
    }
    return true;
  }, [formValues, message]);

  // 初始化 formValues，防止分页切换丢失已填写内容
  useEffect(() => {
    if (item.params?.inputForm) {
      const initialValues: Record<string, any> = {};
      item.params.inputForm.forEach((formItem) => {
        initialValues[formItem.key] = formItem.value ?? formItem.defaultValue ?? '';
      });
      setFormValues((prev) => ({ ...initialValues, ...prev }));
    }
  }, [item.params?.inputForm]);

  const renderFormItem = useCallback((formItem: FormItem) => {
    switch (formItem.type) {
      case 'input':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-font-weight-600 text-text-5">
                {formItem.label}
              </div>
              {formItem.required && <div className="font-bold text-error">*</div>}
              {/* {formItem.label} */}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <Input
                style={{ width: '100%' }}
                disabled={Boolean(!isLastOne || item?.text)}
                placeholder={formItem.description || `请输入${formItem.label}`}
                value={formValues[formItem.key] ?? formItem.value ?? ''}
                onChange={(e) =>
                  setFormValues((prev) => ({ ...prev, [formItem.key]: e.target.value }))
                }
              />
            </div>
          </div>
        );
      case 'numberInput':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
              {formItem.required && <div className="font-bold text-error">*</div>}
              {/* {formItem.label} */}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <InputNumber
                style={{ width: '100%' }}
                disabled={Boolean(!isLastOne || item?.text)}
                placeholder={formItem.description || `请输入${formItem.label}`}
                value={formValues[formItem.key] ?? formItem.value ?? undefined}
                onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
              />
            </div>
          </div>
        );
      case 'select':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
              {formItem.required && <div className="font-bold text-error">*</div>}
              {/* {formItem.label} */}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <Select
                style={{ width: '100%' }}
                disabled={Boolean(!isLastOne || item?.text)}
                placeholder={formItem.description || `请选择${formItem.label}`}
                value={formValues[formItem.key] ?? formItem.value ?? undefined}
                options={formItem.list}
                onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
              />
            </div>
          </div>
        );
      case 'cascader':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
              {formItem.required && <div className="font-bold text-error">*</div>}
              {/* {formItem.label} */}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <Cascader
                style={{ width: '100%' }}
                disabled={Boolean(!isLastOne || item?.text)}
                options={formItem.list}
                placeholder={formItem.description || `请选择${formItem.label}`}
                value={formValues[formItem.key] ?? formItem.value ?? []}
                onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
              />
            </div>
          </div>
        );
      default:
        return null;
    }
  }, [formValues, isLastOne, item?.text]);

  const render = () => (
    <div
      ref={ref}
      className={`mt-2 rounded-xl 
        ${(item?.appLogo && !item.isUser && isPc) ? 'ml-[30px]' : ''}
        ${
          item.isUser
            ? 'ml-auto rounded-[12px_12px_0px_12px] bg-[#62C3FF3D] p-2 font-normal text-[#1D2129]'
            : `rounded-[0px_12px_12px_12px] py-2 font-normal text-[#1D2129] ${
                item.params?.inputForm || item?.interactive?.type == 'userSelect' ? '' : ''
              }`
        } relative max-w-full break-words`}
    >
      {isShow && (
        <div className="w-full">
          {!item.isUser && thoughtListAll && thoughtListAll?.length > 0 && (
            <ThoughtChainALL
              thoughtListAll={thoughtListAll}
              keyArr={keyArr}
              setKeyArr={setKeyArr}
            />
          )}
          {!item?.isTextGenerate &&
            (!item.isUser ? (
              <>
                {/* {JSON.stringify(item, null, 2)} */}
                {item?.interactive?.type == 'userSelect' && (
                  <div className="w-full p-1">
                    <div className="mb-4">
                      <div className="flex items-start justify-start">
                        <div className="mb-2 text-sm font-font-weight-400 text-text-3">
                          {item.interactive?.params?.description}
                        </div>
                        {item.interactive?.params?.description && (
                          <div className="font-bold text-error">*</div>
                        )}
                      </div>
                      <div data-key="userSelect">
                        <Select
                          style={{ minWidth: '200px' }}
                          disabled={
                            Boolean((item.interactive?.params as any)?.userSelectedVal?.length > 0) ||
                            !isLastOne ||
                            Boolean(item?.text)
                          }
                          placeholder={`请选择${item.interactive?.params?.description || ''}`}
                          defaultValue={(item.interactive?.params as any)?.userSelectedVal}
                          options={(item.interactive?.params as any)?.userSelectOptions?.map(
                            (option: UserSelectOptionItemType) => ({
                              label: option.value,
                              value: option.value,
                            }),
                          )}
                          onChange={(value) => setUserSelectValue(value)}
                        />
                      </div>
                    </div>
                    {isLastOne &&
                      !item?.text &&
                      !item?.loading &&
                      !(item.interactive?.params as any)?.userSelectedVal && (
                        <Button
                          type="primary"
                          onClick={() => {
                            if (!userSelectValue) {
                              message.warning('请选择一个选项');
                              // 聚焦到下拉框
                              const selectField = document.querySelector('[data-key="userSelect"]');
                              if (selectField) {
                                const select = selectField.querySelector(
                                  '.ant-select-selector',
                                ) as HTMLElement;
                                if (select) {
                                  select.focus();
                                }
                              }
                              return;
                            }
                            handleSend(userSelectValue, true);
                          }}
                        >
                          提交
                        </Button>
                      )}
                  </div>
                )}

                {item.params?.inputForm && (
                  // (totalItems < 1 || !isPc) ? (
                  (false) ? (
                  <div className="rounded-xl bg-bg-1 p-4">
                    <div className="mb-2 text-sm font-font-weight-400 text-text-3">
                      <pre>
                        {item.interactive?.params?.description}
                      </pre>
                    </div>
                    {item.params.inputForm
                      .slice((currentPage - 1) * pageSize, currentPage * pageSize)
                      .map((formItem: FormItem) => renderFormItem(formItem))}
                    <div className="mt-2 flex items-center justify-end gap-2">
                      {totalPages > 1 && (
                        <>
                          <Button
                            icon={
                              <SvgIcon
                                icon="ai-chat-pre"
                                color={currentPage === 1 ? '#E5E6EB' : '#86909C'}
                                size={32}
                              />
                            }
                            disabled={currentPage === 1}
                            onClick={() => setCurrentPage((prev) => prev - 1)}
                            type="text"
                            className="ml-2 mr-4"
                          />
                          <span style={{ color: '#1D2129' }}>{currentPage}</span>
                          <span
                            style={{ color: currentPage === totalPages ? '#1D2129' : '#86909C' }}
                          >
                            /
                          </span>
                          <span
                            style={{ color: currentPage === totalPages ? '#1D2129' : '#86909C' }}
                          >
                            {totalPages}
                          </span>
                          <Button
                            icon={
                              <SvgIcon
                                icon="ai-chat-next"
                                color={currentPage === totalPages ? '#E5E6EB' : '#86909C'}
                                size={32}
                              />
                            }
                            disabled={currentPage === totalPages}
                            onClick={() => setCurrentPage((prev) => prev + 1)}
                            type="text"
                            className="ml-4 mr-2"
                          />
                        </>
                      )}
                      <Button
                        type="primary"
                        onClick={() => {
                          const formItems = item.params?.inputForm;
                          if (formItems && checkRequiredFields(formItems)) {
                            handleSend(JSON.stringify(formValues), true);
                          }
                        }}
                        className="ml-2"
                        disabled={
                          currentPage !== totalPages ||
                          !isLastOne ||
                          item.loading ||
                          item?.text != ''
                        }
                      >
                        提交
                      </Button>
                    </div>
                  </div>
                  )
                  :
                  (
                    <FormRenderer
                      formItems={item.params.inputForm}
                      description={item.interactive?.params?.description}
                      isLastOne={Boolean(isLastOne)}
                      itemText={Boolean(item?.text || false)}
                      onSend={(values) => handleSend(values, true)}
                      columns={!isPc ? 2 : item.interactive?.params?.column ? item.interactive?.params?.column * 2 : 4} // 默认列数设置为4列
                      labelWidth="130px" // 参数名宽度占比，支持百分比或像素值
                    />
                  )
                )}

                {/* {!item.params?.inputForm && item.params?.type != "userSelect" && */}
                {true &&
                  parts.map((part, idx) =>
                    typeof part === 'string' ? (
                      <ReactMarkdown
                        key={idx}
                        className={`markdown ${mdStyles.markdown} !px-[2px]`}
                        remarkPlugins={
                          [remarkMath, [remarkGfm, { singleTilde: false }], remarkBreaks]
                          // isSupported
                          //   ? [remarkMath, [remarkGfm, { singleTilde: false }], remarkBreaks]
                          //   : [remarkMath, remarkBreaks]
                        }
                        rehypePlugins={[rehypeKatex, rehypeRaw] as any[]}
                        components={markdownComponents}
                      >
                        {part}
                      </ReactMarkdown>
                    ) : (
                      <ToolCallCollapse
                        key={part.id}
                        id={part.id}
                        tool={item.toolJson?.[part.id] || {
                          id: part.id,
                          toolName: '',
                          toolAvatar: '',
                          params: '',
                          response: '',
                          functionName: ''
                        }}
                        functionName={item.toolJson?.[part.id]?.toolName || item.toolJson?.[part.id]?.functionName || ''}
                        params={item.toolJson?.[part.id]?.params}
                        response={item.toolJson?.[part.id]?.response}
                      />
                    ),
                  )}
              </>
            ) : (
              <div
                style={{
                  padding: '5px',
                  whiteSpace: 'pre-wrap',
                  wordWrap: 'break-word',
                  overflowWrap: 'break-word',
                }}
              >
                {item.text}
              </div>
            ))}
          {item?.isTextGenerate && (
            <div style={{ padding: '5px' }}>
              {item.text}
              <SvgIcon icon="ic_rj_loading2" color="#fff" size={20} />
            </div>
          )}
          {/* <div className={isExpanded ? '' : 'flex flex-wrap items-center'}> */}
          {!item.isUser && isQuote && item.quote && item.quote.length > 0 && (
            <div className="mt-[11px]">
              <Reference
                files={item.quote}
                onChange={handleReferenceChange}
                defaultCollectionId={defaultCollectionId}
                initCollectionId={initCollectionId}
              />
            </div>
          )}
          {!item.isUser && item?.text && !item?.loading && index !== 0 && (
            <div className={styles['hr-container']}>
              <div className={styles['hr-line']}></div>
            </div>
          )}
          <div className="flex flex-wrap items-center">
            {!item.isUser && item?.text && !item?.loading && index !== 0 && (
              <>
                <SvgIcon icon="ai-chat-warning" size={14}></SvgIcon>
                <span className="pl-1 text-[12px] text-grays">本答案由AI生成，请谨慎参考</span>
              </>
            )}
            <div
              className={`ml-auto mr-1 flex items-center justify-end ${isExpanded ? 'mt-2' : ''}`}
            >
              {!item.loading && !item.isUser && item?.text && index !== 0 && (
                <CustomControl
                  isRobot={true}
                  data={item.text || ''}
                  item={item}
                  chatId={item.chatId}
                  dataId={item.dataId}
                  defaultLike={item?.userGoodFeedback === 'yes'}
                  defaultDislike={!!item?.userBadFeedback}
                  onDelete={deleteMessage ? () => deleteMessage(index) : undefined}
                  onRefresh={reFreshAnswer ? () => reFreshAnswer(index) : undefined}
                  workflowDebug={workflowDebug}
                />
              )}
            </div>
          </div>
          {/* {!item.isUser && item?.text && !item?.loading && index !== 0 && (
            <>
              <span className="text-[#8E93A4] px-2.5 text-[10px]">
                本答案由AI生成，请谨慎参考
              </span>
            </>
          )} */}
          {!item?.loading &&
            isLastOne &&
            guessQuestions &&
            guessQuestions.length > 0 &&
            onQuestionClick && (
              <>
                <GuessYouWantToAsk questions={guessQuestions} onQuestionClick={onQuestionClick} />
              </>
            )}
        </div>
      )}
    </div>
  );

  useEffect(() => {
    // 最后一个消息大小变化后触发滚动到最后
    if (isLastOne) {
      scrollToBottom && scrollToBottom();
    }
  }, [size?.height, isLastOne, scrollToBottom]);

  // 分页相关 state
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 3;
  const totalItems = item.params?.inputForm?.length || 0;
  const totalPages = Math.ceil(totalItems / pageSize);

  return item.isUser
    ? item.text && (
        <Tooltip
          mouseLeaveDelay={0.3}
          color="#fff"
          title={
            <CustomControl
              isRobot={false}
              data={item.text || ''}
              onDelete={deleteMessage ? () => deleteMessage(index) : undefined}
            />
          }
          placement="bottomRight"
        >
          {render()}
        </Tooltip>
      )
    : render();
};

export default React.memo(MessageItem);
